import { createStorage } from '@/utils/storage'
import { ACCESS_TOKEN, USER_NAME } from '@/store/mutationTypes'
import { LoginName } from '@/router/modules/login'
import router from '@/router'

const Storage = createStorage()

const StoreModel = {
  namespaced: true,
  state: {
    token: Storage.get(ACCESS_TOKEN, ''),
    username: Storage.get(USER_NAME, '')
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      Storage.set(ACCESS_TOKEN, token || '')
    },
    SET_USERNAME: (state, name) => {
      state.username = name
      Storage.set(USER_NAME, name || '')
    }
  },
  actions: {
    /**
     * 登录
     */
    handleLogin({ commit }, data = '') {
      commit('SET_TOKEN', data)
      commit('SET_USERNAME', data)
    },

    /**
     * 登出
     */
    handleLoginOut({ commit }, data = { goLogin: true }) {
      commit('SET_TOKEN', '')
      commit('SET_USERNAME', '')
      Storage.remove(ACCESS_TOKEN)
      Storage.remove(USER_NAME)

      if (data.goLogin) {
        router.push({ name: LoginName })
      }
    }
  }
}

export default StoreModel
